package com.topisv.tms.service.stock.reverse;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.hibernate.ejb.criteria.predicate.ComparisonPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.stock.reverse.ReverseBill;
import com.topisv.tms.entity.stock.reverse.ReverseBillItem;
import com.topisv.tms.repository.AreaGroupDao;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillDao;
import com.topisv.tms.repository.stock.reverse.ReverseBillItemDao;

/**
 * 冲正单_service
 * @author ch
 *
 */
@Component
@Transactional(readOnly = true)
public class ReverseBillService {
	
	@Autowired
	private ReverseBillDao reverseBillDao;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private AreaGroupDao areaGroupDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private ReverseBillItemDao reverseBillItemDao;

	@Transactional(readOnly = false )
	public void updateWarehouseCode(ReverseBill reverseBill,String warehouseCode){
		reverseBill.setIsAllocated("Y");
		reverseBill.setWarehouseCode(warehouseCode);
		reverseBillDao.save(reverseBill);
		List<ReverseBillItem> items = reverseBillItemDao.loadByBillCode(reverseBill.getBillCode());
		for(ReverseBillItem item:items){
			item.setWarehouseCode(reverseBill.getWarehouseCode());
		}
		reverseBillItemDao.save(items);
	}
	/**
	 * 分页查询
	 * @param param
	 * @param curPage
	 * @param length
	 * @return
	 */
	public Page<ReverseBill> loadTask(Map<String, Object> params,int pageNumber, int pageSize) {
		Sort sort = new Sort(Sort.Direction.DESC,"id");
	    PageRequest pageRequest = new PageRequest(pageNumber-1, pageSize, sort);
	    Specification<ReverseBill> spec =this.getWhereClause(params);
	    Page<ReverseBill> page = this.reverseBillDao.findAll(spec, pageRequest);
	    List<ReverseBill> taskList=page.getContent();
	    for (ReverseBill bill : taskList) {
			this.setDetail(bill);
		}
	    return page;
	}

	/**
	 * 条件封装
	 * @param params
	 * @return
	 */
	private Specification<ReverseBill> getWhereClause(final Map<String, Object> params) {
		 return new Specification<ReverseBill>(){
		    @Override
		    public Predicate toPredicate(Root<ReverseBill> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
		      Predicate pre = cb.conjunction();
		      
		      //customerCodes
		      String customerCodes=(String) params.get("customerCodes");
		      if(StringUtils.isNotBlank(customerCodes)){
		    	  String[] customerCodeSplit = customerCodes.split(":");
				  ComparisonPredicate[] tempCustomerCode = new ComparisonPredicate[customerCodeSplit.length];
				  int i = 0;
				  for (String _customerCode : customerCodeSplit) {
					 tempCustomerCode[i] = (ComparisonPredicate) cb.equal(r.get("customerCode"), _customerCode);
					 i++;
				  }
				  pre.getExpressions().add(cb.or(tempCustomerCode)); 
		      }
		      
		      //areagroups
		      String areagroups=(String) params.get("areagroups");
		      if(StringUtils.isNotBlank(areagroups)){
		    	  String[] areagroupSplit = areagroups.split(":");
				  ComparisonPredicate[] areagroupArray = new ComparisonPredicate[areagroupSplit.length];
				  int j = 0;
				  for (String _areagroup : areagroupSplit) {
						areagroupArray[j] = (ComparisonPredicate) cb.equal(r.get("warehouseCode"), _areagroup);
						j++;
				  }
				  pre.getExpressions().add(cb.or(areagroupArray));
		      }
			  
			  //customerCode
		      String customerCode=(String) params.get("customerCode");
		      if(StringUtils.isNotBlank(customerCode)){
			         pre.getExpressions().add(cb.equal(r.get("customerCode"),customerCode));
			  }
		      
		      //warehouseCode
		      String warehouseCode=(String) params.get("warehouseCode");
		      if(StringUtils.isNotBlank(warehouseCode)){
			         pre.getExpressions().add(cb.equal(r.get("warehouseCode"),warehouseCode));
			  }
		      
              //createTime
		      Date fromDate= (Date) params.get("fromDate");
		      if (fromDate != null) {
		        pre.getExpressions().add(cb.greaterThanOrEqualTo(r.<Date>get("createTime"), fromDate));
		      }
		      Date toDate= (Date) params.get("toDate");
		      if (toDate != null) {
		        pre.getExpressions().add(cb.lessThanOrEqualTo(r.<Date>get("createTime"), toDate));
		      }
		      
		      //status
		      String status=(String) params.get("status");
		      if(StringUtils.isNotBlank(status)){
		         pre.getExpressions().add(cb.equal(r.get("status"),status));
			  }
		      
		      //billCode
		      String billCode=(String) params.get("billCode");
		      if(StringUtils.isNotBlank(billCode)){
					pre.getExpressions().add(cb.equal(r.get("billCode"),billCode));
			  }
		      return pre;
		    }
		  };
	}

	/**
	 * 设置属性
	 * @param bill
	 */
	private void setDetail(ReverseBill bill) {
		//customer
		String customerCode=bill.getCustomerCode();
		Customers customer=this.customersDao.findByCustomerCode(customerCode);
		bill.setCustomer(customer);
		
		//warehouse
		String warehouseCode=bill.getWarehouseCode();
		AreaGroup warehouse=this.areaGroupDao.findByGroupCode(warehouseCode);
		bill.setWarehouse(warehouse);
		
		//creater
		User user=this.userDao.findByJobuuid(bill.getCreaterUuid());
		bill.setCreater(user);
	}

	/**
	 * 查询
	 * @param billId
	 * @return
	 */
	public ReverseBill loadById(Long billId) {
		return this.reverseBillDao.findOne(billId);
	}

}
